package com.cws4cloud.cws.common.security.component;

import cn.hutool.core.util.StrUtil;
import com.cws4cloud.cws.common.core.tenant.CwsTenantProperties;
import com.cws4cloud.cws.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @ClassName: RedisAutoCacheManager
 * @Description: 重载获取缓存的方法添加租户信息
 * @Author zhlj
 * @Company:digitalchina
 * @Date 2021/1/27 10:09
 */
@Slf4j
public class RedisAutoCacheManager extends RedisCacheManager{

	@Autowired
	private CwsTenantProperties properties;

	public RedisAutoCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
		super(cacheWriter, defaultCacheConfiguration);
	}


	/**
	 * 从上下文中获取租户ID，重写@Cacheable value 值
	 * @param name
	 * @return
	 */
	@Override
	public Cache getCache(String name) {
		if (properties.isEnable()&&StrUtil.isNotBlank(SecurityUtils.getTenantId())){
			return super.getCache(SecurityUtils.getTenantId() + StrUtil.COLON + name );
		} else {
			return super.getCache(name);
		}
	}
}
